//
//  YWNoQrcodeLedgerLocationDetailViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 17/2/22.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWNoQrcodeLedgerLocationDetailViewController.h"
#import "YWMatchMissionsViewController.h"
#import "YWCreateTempMissionTableViewController.h"
#import "YWPostTroubleTableViewController.h"
#import "YWLocationInspectionRecordMoreTableViewController.h"
#import "YWLocationKeepWatchRecordMoreTableViewController.h"
#import "YWLocationTroubleRecordMoreTableViewController.h"
#import "YWLocationCheckRecordMoreTableViewController.h"
#import "YWKeepWatchLocationRecordDetailTableViewController.h"
#import "YWInspecLocationRecordDetailTableViewController.h"
#import "YWTemTroubleDetailTableViewController.h"
#import "YWCirculationDetailViewController.h"
#import "YWAssetsInventoryDetailsTableViewController.h"

#import "YWConst.h"
#import "YWMacro.h"
#import "YWCommonTool.h"

#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWKeepWatchMissionManager.h"
#import "YWInspectionMissionManager.h"
#import "YWAssetCheckManager.h"
#import "YWMissionManager.h"

#import "YWAssetCheckRecord.h"
#import "YWFunctionManager.h"
#import "YWFunctionModel.h"
#import "YWEquipmentManager.h"
#import "YWNoQrcodeRights.h"
#import "YWLoginTool.h"
#import "YWReportTroubleModel.h"
#import "YWReportTroubleManager.h"

#import "UIImageView+WebCache.h"
#import "UIColor+CustomColors.h"
#import "MJRefresh.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "NSDate+YYAdd.h"
#import "BHBPopView.h"

#import "YWEmptyTableViewCell.h"
#import "YWNoQrcodeLedgerLocationRecordTableViewCell.h"
#import "YWLedgerPostTroubleTableViewCell.h"

@interface YWNoQrcodeLedgerLocationDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray * dataSource;
//headView
@property (nonatomic, strong) UIView * headView;
@property (nonatomic, strong) UIView * locationView;
@property (nonatomic, strong) UIImageView * buildingImageView;
@property (nonatomic, strong) UILabel * buildingLabel;
@property (nonatomic, strong) UILabel * locationLabel;
@property (nonatomic, strong) UIView * segmentView;
@property (nonatomic, strong) UILabel * maintainLabel;
@property (nonatomic, strong) UISegmentedControl *segmentedControl;
//footView
@property (nonatomic, strong) UIView * footView;
//@property (nonatomic, strong) UIButton * addButton;//+号按钮
@property (nonatomic, strong) UILabel * seeMoreLabel;
@end

@implementation YWNoQrcodeLedgerLocationDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"位置详情";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    [self setupTableView];
    [self setupData];
}

- (void)setupTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    [_tableView registerClass:[YWLedgerPostTroubleTableViewCell class] forCellReuseIdentifier:YWLedgerPostTroubleTableViewCellIdentifier];
    [_tableView registerClass:[YWNoQrcodeLedgerLocationRecordTableViewCell class] forCellReuseIdentifier:YWNoQrcodeLedgerLocationRecordTableViewCellIdentifier];
    [_tableView registerClass:[YWEmptyTableViewCell class] forCellReuseIdentifier:YWEmptyTableViewCellIdentifier];
    
    _tableView.backgroundColor = [UIColor customBackgroudColor];
    _tableView.tableHeaderView = self.headView;
    _tableView.tableFooterView = self.footView;
    _tableView.tableFooterView.hidden = YES;
    _tableView.estimatedRowHeight = 44.0f;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    
//    [self.navigationController.view addSubview:self.addButton];
}

- (void)setupData{
    [self refreshTop];
    [self loadDataWithSegement:0];
}

- (void)refreshTop
{
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    YWWeakSelf(weakSelf);
    dispatch_group_t group = dispatch_group_create();
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //巡查
        dispatch_group_enter(group);
        [[YWKeepWatchMissionManager shareManager] requestPatrolPointRecord:self.locationId page:1 pageSize:10 complete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        //巡更
        dispatch_group_enter(group);
        [[YWInspectionMissionManager shareManager] requestInspectionLocationRecord:self.locationId page:1 pageSize:10 complete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        
        //请求报障记录，locationId
        dispatch_group_enter(group);
        [[YWReportTroubleManager shareManager] requestPostTroubleWithLocationId:self.locationId page:1 pageSize:10 completeBlock:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        //请求清点记录
        dispatch_group_enter(group);
        [[YWAssetCheckManager shareManager] requestAssetCheckRecordWithPage:1 pageSize:10 locationId:weakSelf.locationId WithComplete:^(BOOL success) {
            dispatch_group_leave(group);
        }];
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }
            else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            [weakSelf.dataSource removeAllObjects];
            [self loadDataWithSegement:_segmentedControl.selectedSegmentIndex];
            [weakSelf.tableView reloadData];
        });
    });
}

#pragma mark --- tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count>0?self.dataSource.count:1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count>0?[self.dataSource[section] count]:1;;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self.dataSource count]>0) {
        id object =  self.dataSource[indexPath.section][indexPath.row];
        if ([object isKindOfClass:[YWInspectionEquipmentRecord class]]) {
            //巡查
            YWNoQrcodeLedgerLocationRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerLocationRecordTableViewCellIdentifier];
            cell.inspectionRecord = (YWInspectionEquipmentRecord*)object;
            return cell;
        }else if ([object isKindOfClass:[YWPatrolPointRecord class]]){
            //巡更
            YWNoQrcodeLedgerLocationRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerLocationRecordTableViewCellIdentifier];
            cell.patrolRecord = (YWPatrolPointRecord*)object;
            return cell;
        }else if ([object isKindOfClass:[YWReportTroubleModel class]]){
            //地址报障
            YWLedgerPostTroubleTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWLedgerPostTroubleTableViewCellIdentifier];
            cell.reportTroulbe = (YWReportTroubleModel*)object;
            return cell;
        }else{
            //清点
            YWNoQrcodeLedgerLocationRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:YWNoQrcodeLedgerLocationRecordTableViewCellIdentifier];
            cell.checkRecord = (YWAssetCheckRecord*)object;
            return cell;
        }
    }else{
        YWEmptyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:YWEmptyTableViewCellIdentifier];
        cell.backgroundColor = [UIColor customBackgroudColor];
        return cell;
    }
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if ([self.dataSource count]>0) {
//        id object = self.dataSource[indexPath.section][indexPath.row];
//        if ([object isKindOfClass:[YWReportTroubleModel class]]) {
//            //位置报障
//            return [tableView fd_heightForCellWithIdentifier:YWLedgerPostTroubleTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWLedgerPostTroubleTableViewCell *cell) {
//                cell.reportTroulbe = (YWReportTroubleModel*)object;
//            }];
//        }else{
//            return [tableView fd_heightForCellWithIdentifier:YWNoQrcodeLedgerLocationRecordTableViewCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNoQrcodeLedgerLocationRecordTableViewCell *cell) {
//                if ([object isKindOfClass:[YWInspectionEquipmentRecord class]]){
//                    //巡查
//                    cell.inspectionRecord = (YWInspectionEquipmentRecord*)object;
//                }else if ([object isKindOfClass:[YWPatrolPointRecord class]]){
//                    //巡更
//                    cell.patrolRecord = (YWPatrolPointRecord*)object;
//                }else{
//                    //清点
//                    cell.checkRecord = (YWAssetCheckRecord*)object;
//                }
//            }];
//        }
//    }else{
//        return 150;
//    }
//}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([self.dataSource count]>0) {
        static NSString* HeaderIdentifier = @"YWNoQrcodeLedgerLocationDetailViewControllerForHeaderInSection";
        UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
        if (headerView == nil) {
            headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
            headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
            UILabel* label = [[UILabel alloc] init];
            label.textAlignment = NSTextAlignmentLeft;
            label.textColor = [UIColor blackColor];
            label.tag = 2016;
            label.font = KTitleFont;
            [headerView addSubview:label];
        }
        
        NSString *headText = [self titleForHeaderInSection:section];
        UILabel* label = [headerView viewWithTag:2016];
        label.text = headText;
        label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
        return headerView;
    }else{
        return nil;
    }
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *array = [self.dataSource[section] count]>0?self.dataSource[section]:nil;
    id object = array.count?array[0]:nil;
    if ([object isKindOfClass:[YWReportTroubleModel class]]) {
        YWReportTroubleModel * reportTrouble = array.count?array[0]:nil;
        NSString *time = [YWCommonTool showChineseFormatterDate:reportTrouble.reportTime/1000];
        NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:reportTrouble.reportTime/1000].weekday;
        NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
        NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
        return title;
    }else if ([object isKindOfClass:[YWInspectionEquipmentRecord class]]){
        YWInspectionEquipmentRecord *equipmentRecord = array.count?array[0]:nil;
        NSString *time = [YWCommonTool showChineseFormatterDate:equipmentRecord.executeTime/1000];
        NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:equipmentRecord.executeTime/1000].weekday;
        NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
        NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
        return title;
    }else if([object isKindOfClass:[YWPatrolPointRecord class]]){
        YWPatrolPointRecord *patrolRecord = array.count?array[0]:nil;
        NSString *time = [YWCommonTool showChineseFormatterDate:patrolRecord.patrolTime/1000];
        NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:patrolRecord.patrolTime/1000].weekday;
        NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
        NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
        return title;
    }else{
        YWAssetCheckRecord * checkRecord = array.count?array[0]:nil;
        NSString *time = [YWCommonTool showChineseFormatterDate:checkRecord.createTime/1000];
        NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:checkRecord.createTime/1000].weekday;
        NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
        NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
        return title;
    }
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    if ([self.dataSource count]>0) {
        return 35;
    }else{
        return 0.01;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //跳转至详情页面
    if (self.dataSource.count>0) {
        id object = self.dataSource[indexPath.section][indexPath.row];
        if ([object isKindOfClass:[YWPatrolPointRecord class]]) {
            //巡更记录详情
            YWKeepWatchLocationRecordDetailTableViewController* keepWatchDetailVC = [[YWKeepWatchLocationRecordDetailTableViewController alloc] init];
            keepWatchDetailVC.patrolPointRecord = (YWPatrolPointRecord*)object;
            [self.navigationController pushViewController:keepWatchDetailVC animated:YES];
        }else if ([object isKindOfClass:[YWInspectionEquipmentRecord class]]){
            //巡查记录详情
            YWInspecLocationRecordDetailTableViewController * inspectionRecordDetailVC = [[YWInspecLocationRecordDetailTableViewController alloc] init];
            inspectionRecordDetailVC.inspectionEquipmentRecord = (YWInspectionEquipmentRecord*)object;
            [self.navigationController pushViewController:inspectionRecordDetailVC animated:YES];
        }else if ([object isKindOfClass:[YWReportTroubleModel class]]){
            //报障记录详情
            YWReportTroubleModel *reportTrouble = (YWReportTroubleModel*)object;
            if (reportTrouble.troubleId<=0 && reportTrouble.troubleStatus == YWTroubleMissionStatusFinish) {
                YWTemTroubleDetailTableViewController *tempTroubleVC = [[YWTemTroubleDetailTableViewController alloc] init];
                tempTroubleVC.reportTrouble = reportTrouble;
                [self.navigationController pushViewController:tempTroubleVC animated:YES];
            }else{
                YWCirculationDetailViewController *circulationDetailVC = [[YWCirculationDetailViewController alloc] init];
                circulationDetailVC.isNotShowHandleButton = YES;
                circulationDetailVC.troubleMissionModel = reportTrouble.troubleMission;
                [self.navigationController pushViewController:circulationDetailVC animated:YES];
            }
        }else if ([object isKindOfClass:[YWAssetCheckRecord class]]){
            //清点记录详情
            YWAssetsInventoryDetailsTableViewController *checkRecordDetailVC = [[YWAssetsInventoryDetailsTableViewController alloc] init];
            checkRecordDetailVC.checkRecord = (YWAssetCheckRecord*)object;
            checkRecordDetailVC.needPopBack = YES;
            [self.navigationController pushViewController:checkRecordDetailVC animated:YES];
        }
    }
}

#pragma mark ----标签栏的响应事件
- (void)segmentControlEvent:(UISegmentedControl *)segmentControl{
    [self loadDataWithSegement:segmentControl.selectedSegmentIndex];
}

- (void)loadDataWithSegement:(NSInteger)segement{
    //切换数据源用
    YWLog(@"segmentControl %ld",(long)segement);
    if (segement == 0) {
        [self.dataSource removeAllObjects];
        //巡更
        NSArray * keepWatchArray = [[YWMissionManager shareManager] keepWatchAndInspectRecordsInLedgerLocationDetailWithLocationId:self.locationId andPage:1 type:YWKeepWatchOrInspectionTypeKeepWatch];
        [self.dataSource addObjectsFromArray:keepWatchArray];
        self.seeMoreLabel.text = @"查看更多巡更记录";
    }else if (segement == 1){
        [self.dataSource removeAllObjects];
        //巡查
        NSArray * inspectionArray = [[YWMissionManager shareManager] keepWatchAndInspectRecordsInLedgerLocationDetailWithLocationId:self.locationId andPage:1 type:YWKeepWatchOrInspectionTypeInspection];
        [self.dataSource addObjectsFromArray:inspectionArray];
        self.seeMoreLabel.text = @"查看更多巡查记录";
    }else if (segement == 2){
        [self.dataSource removeAllObjects];
        //位置报障
        NSArray * troublesArray = [[YWReportTroubleManager shareManager] getReportTroubleWithLocationId:self.locationId page:1];
        [self.dataSource addObjectsFromArray:troublesArray];
        self.seeMoreLabel.text = @"查看更多报障记录";
    }else{
        [self.dataSource removeAllObjects];
        //清点
        NSArray * checkRecordArray = [[YWAssetCheckManager shareManager] assetCheckWithPage:1 locationId:self.locationId];
        [self.dataSource addObjectsFromArray:checkRecordArray];
        self.seeMoreLabel.text = @"查看更多清点记录";
    }
    NSMutableArray * countArray = [NSMutableArray array];
    [self.dataSource enumerateObjectsUsingBlock:^(NSArray *  _Nonnull array, NSUInteger idx, BOOL * _Nonnull stop) {
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [countArray addObject:obj];
            if (countArray.count>9) {
                *stop = YES;
            }
            }];
    }];
    if (countArray.count>9) {
        self.tableView.tableFooterView.hidden = NO;
    }else{
        self.tableView.tableFooterView.hidden = YES;
    }
    [self.tableView reloadData];
}
/*
- (void)addButtonTouchEvent:(UIButton*)sender{
    
        BHBItem * Item1 = [[BHBItem alloc]initWithTitle:@"" Icon:@""];
        BHBItem * Item2 = [[BHBItem alloc]initWithTitle:@"" Icon:@""];
        BHBItem * Item3 = [[BHBItem alloc]initWithTitle:@"" Icon:@""];
        BHBItem * inspectionItem = [[BHBItem alloc]initWithTitle:@"巡查" Icon:@"profile_patrol"];
        BHBItem * keepWatchItem = [[BHBItem alloc]initWithTitle:@"巡更" Icon:@"patroling"];
        BHBItem * myTroublesItem = [[BHBItem alloc]initWithTitle:@"报障" Icon:@"profile_postTrouble"];
        //        BHBItem * cancelItem = [[BHBItem alloc]initWithTitle:@"取消" Icon:@"tabbar_compose_background_icon_close"];
        //添加popview
        [BHBPopView showToView:self.view.window withItems:@[Item1,Item2,Item3,keepWatchItem,inspectionItem,myTroublesItem] andSelectBlock:^(BHBItem *item) {
            if ([item isKindOfClass:[BHBGroup class]]) {
                YWLog(@"选中%@分组",item.title);
            }else{
                if ([item.title isEqualToString:@"巡查"]) {
                    YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdInspection];
                    if (function.offOrOn == YWFunctionStatusOn) {
                        //位置巡查任务
                        NSArray *inspectionMissions = nil;
                        if (self.qrcodeId) {
                            inspectionMissions = [[YWInspectionMissionManager shareManager] matchInspectionMissionsWithQrcodeID:self.qrcodeId orLocationId:0];
                        }else{
                            NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeInspectionKey] integerValue];
                            if (value!=1) {
                                inspectionMissions = [[YWInspectionMissionManager shareManager] matchInspectionMissionsWithQrcodeID:nil orLocationId:self.locationId];
                            }
                        }
                        if (inspectionMissions.count>0) {
                            YWMatchMissionsViewController *matchMissionVC = [[YWMatchMissionsViewController alloc] init];
                            matchMissionVC.matchMissions = inspectionMissions;
                            matchMissionVC.qrCodeId = self.qrcodeId;
                            matchMissionVC.locationId = self.locationId;
                            [self.navigationController pushViewController:matchMissionVC animated:YES];
                        }else{
                            YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
//                            tempMissionVC.qrcodeId = self.qrcodeId;
                            tempMissionVC.locationId = self.locationId;
                            tempMissionVC.isLocationInspection = YES;
                            tempMissionVC.isEquipmentInspection = NO;
                            tempMissionVC.maintenanceType = YWMaintenanceTypePatrol;
                            [self.navigationController pushViewController:tempMissionVC animated:YES];
                        }
                    }else{
                        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:@"功能已关闭。如需再次使用巡查功能，您可从“设置-功能”中再次打开。" preferredStyle:UIAlertControllerStyleAlert];
                        [alertController addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
                        [self presentViewController:alertController animated:YES completion:nil];
                    }
                }else if ([item.title isEqualToString:@"巡更"]){
                    //巡更任务
                    YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdKeepWatch];
                    if (function.offOrOn == YWFunctionStatusOn) {
                        NSArray *keepWatchMissions = nil;
                        if (self.qrcodeId) {
                            keepWatchMissions = [[YWKeepWatchMissionManager shareManager] matchKeepWatchMissionsWithQrcodeID:self.qrcodeId orLocationId:0];
                        }else{
                            NSInteger value = [[[NSUserDefaults standardUserDefaults] objectForKey:KYWNoQrcodeTypeKeepWatchKey] integerValue];
                            if (value!=1) {
                                keepWatchMissions = [[YWKeepWatchMissionManager shareManager] matchKeepWatchMissionsWithQrcodeID:nil orLocationId:self.locationId];
                            }
                        }
                        if (keepWatchMissions.count>0) {
                            YWMatchMissionsViewController *matchMissionVC = [[YWMatchMissionsViewController alloc] init];
                            matchMissionVC.matchMissions = keepWatchMissions;
                            matchMissionVC.qrCodeId = self.qrcodeId;
                            matchMissionVC.locationId = self.locationId;
                            [self.navigationController pushViewController:matchMissionVC animated:YES];
                        }else{
                            YWCreateTempMissionTableViewController *tempMissionVC = [[YWCreateTempMissionTableViewController alloc] init];
                            tempMissionVC.maintenanceType = YWMaintenanceTypeKeepWatch;
                            tempMissionVC.locationId = self.locationId;
//                            tempMissionVC.qrcodeId = self.qrcodeId;
                            [self.navigationController pushViewController:tempMissionVC animated:YES];
                        }
                    }else{
                        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:@"功能已关闭。如需再次使用巡更功能，您可从“设置-功能”中再次打开。" preferredStyle:UIAlertControllerStyleAlert];
                        [alertController addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
                        [self presentViewController:alertController animated:YES completion:nil];
                    }
                }else if ([item.title isEqualToString:@"报障"]){
                    YWFunctionModel * function = [[YWFunctionManager shareManager] getFunctionModelWithFunctionModelId:YWFunctionIdPostTrouble];
                    if (function.offOrOn == YWFunctionStatusOn) {
                        NSArray *allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:self.locationId];;
                        YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];
                        postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;
                        postTroublevc.equipmentArray = allEquipmentArray;
                        postTroublevc.qrCodeId = _qrcodeId;
                        postTroublevc.locationId = self.locationId;
                        postTroublevc.shouldPopBack = YES;
                        [self.navigationController pushViewController:postTroublevc animated:YES];
                    }else{
                        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:@"功能已关闭。如需再次使用报障功能，您可从“设置-功能”中再次打开。" preferredStyle:UIAlertControllerStyleAlert];
                        [alertController addAction:[UIAlertAction actionWithTitle:@"好" style:UIAlertActionStyleCancel handler:nil]];
                        [self presentViewController:alertController animated:YES completion:nil];
                    }
                }
            }
        }];
}
*/
- (void)footViewGestureRecognizer:(UITapGestureRecognizer*)sender{
    if ([self.seeMoreLabel.text isEqualToString:@"查看更多巡更记录"]) {
        YWLocationKeepWatchRecordMoreTableViewController * keepWatchMoreVC = [[YWLocationKeepWatchRecordMoreTableViewController alloc] init];
        keepWatchMoreVC.locationId = self.locationId;
        [self.navigationController pushViewController:keepWatchMoreVC animated:YES];
    }else if ([self.seeMoreLabel.text isEqualToString:@"查看更多巡查记录"]){
        YWLocationInspectionRecordMoreTableViewController * inspectionMoreVC = [[YWLocationInspectionRecordMoreTableViewController alloc] init];
        inspectionMoreVC.locationId = self.locationId;
        [self.navigationController pushViewController:inspectionMoreVC animated:YES];
    }else if ([self.seeMoreLabel.text isEqualToString:@"查看更多报障记录"]){
        YWLocationTroubleRecordMoreTableViewController * troubleMoreVC = [[YWLocationTroubleRecordMoreTableViewController alloc] init];
        troubleMoreVC.locationId = self.locationId;
        [self.navigationController pushViewController:troubleMoreVC animated:YES];
    }else{
        YWLocationCheckRecordMoreTableViewController * checkRecordMoreVC = [YWLocationCheckRecordMoreTableViewController new];
        checkRecordMoreVC.locationId = self.locationId;
        [self.navigationController pushViewController:checkRecordMoreVC animated:YES];
    }
}

#pragma mark --- 懒加载
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (UIView*)headView{
    if (!_headView) {
        UIView * headView = [[UIView alloc] init];
        headView.backgroundColor = [UIColor customBackgroudColor];
        
        //locationView
        NSInteger locationId = self.locationId;
        YWBuilding* building = [[YWBuildingManager shareManager] buildingWithLocationId:locationId];
        NSString* downloadUrl = [YWCommonTool pictureDownloadUrl:building.surfacePicture];
        [self.buildingImageView sd_setImageWithURL:[NSURL URLWithString:downloadUrl] placeholderImage:[UIImage imageNamed:@"placeholder_buliding"]];
        CGFloat imageSize = kLabelH*2;
        [self.buildingImageView setFrame:CGRectMake(kMarginW, kGapH, imageSize, imageSize)];
        
        self.buildingLabel.text = building.buildingName.length>0?building.buildingName:@"未知楼盘";
        CGFloat buildingW = SCREEN_WIDTH-kMarginW*3-imageSize;
        CGFloat buildingH = [YWCommonTool getHeightOfLabel:self.buildingLabel.text andWidth:buildingW andFont:self.buildingLabel.font andMinHeight:kLabelH];
        [self.buildingLabel setFrame:CGRectMake(CGRectGetMaxX(self.buildingImageView.frame)+kMarginW, 2*kGapH, buildingW, buildingH)];
        
        NSString* position = [[YWBuildingManager shareManager] areaLocationNobuildingWithId:locationId];
        NSString *locationStr = position.length ? position : @"位置未填写";
        self.locationLabel.text = locationStr;
        CGFloat locationW = SCREEN_WIDTH - 2*kMarginW;
        CGFloat locationH = [YWCommonTool getHeightOfLabel:self.locationLabel.text andWidth:locationW andFont:self.locationLabel.font andMinHeight:kLabelH];
        [self.locationLabel setFrame:CGRectMake(kMarginW, 2*kGapH+imageSize, locationW, locationH)];
        
        [self.locationView addSubview:self.buildingImageView];
        [self.locationView addSubview:self.buildingLabel];
        [self.locationView addSubview:self.locationLabel];
        CGFloat locationViewH = kGapH*3 + imageSize + locationH;
        [self.locationView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, locationViewH)];
        [headView addSubview:self.locationView];
        
        //segmentView
        CGFloat segmentViewHeight = 96.0;
        CGFloat maintainLabelWidth = 80;
        
        [self.segmentView setFrame:CGRectMake(0,locationViewH+kGapH, SCREEN_WIDTH, segmentViewHeight)];
        [self.maintainLabel setFrame:CGRectMake(kGapH, kGapH, maintainLabelWidth, kLabelH)];
        self.maintainLabel.text = @"维保记录";
        
        [self.segmentedControl setFrame:CGRectMake(kGapH, kGapH*2+kLabelH, SCREEN_WIDTH-kGapH*2, KbottomViewH)];
        [self.segmentView addSubview:self.maintainLabel];
        [self.segmentView addSubview:self.segmentedControl];
        [headView addSubview:self.segmentView];
        [headView setFrame:CGRectMake(0, 0, SCREEN_WIDTH,CGRectGetMaxY(self.segmentView.frame))];
        _headView = headView;
    }
    return _headView;
}

- (UIView*)locationView{
    if (!_locationView) {
        UIView * locationView = [[UIView alloc] init];
        locationView.backgroundColor = [UIColor whiteColor];
        _locationView = locationView;
    }
    return _locationView;
}

- (UIImageView*)buildingImageView
{
    if (!_buildingImageView) {
        UIImageView* buildingImageView = [[UIImageView alloc] init];
        buildingImageView.layer.masksToBounds = YES;
        buildingImageView.layer.cornerRadius = 22.0;
        _buildingImageView = buildingImageView;
    }
    return _buildingImageView;
}

- (UILabel*)buildingLabel
{
    if (!_buildingLabel) {
        UILabel* buildingLabel = [[UILabel alloc] init];
        buildingLabel.font = KTitleFont;
        buildingLabel.numberOfLines = 0;
        _buildingLabel = buildingLabel;
    }
    return _buildingLabel;
}

- (UILabel*)locationLabel
{
    if (!_locationLabel) {
        UILabel* locationLabel = [[UILabel alloc] init];
        locationLabel.font = KSmallContentFont;
        locationLabel.textColor = [UIColor customTextGrayColor];
        locationLabel.numberOfLines = 0;
        _locationLabel = locationLabel;
    }
    return _locationLabel;
}

- (UIView*)segmentView{
    if (!_segmentView) {
        UIView * segmentView = [[UIView alloc] init];
        segmentView.backgroundColor = [UIColor whiteColor];
        _segmentView = segmentView;
    }
    return _segmentView;
}

- (UILabel*)maintainLabel{
    if (!_maintainLabel) {
        UILabel * maintainLabel = [[UILabel alloc] init];
        maintainLabel.font = kContentFont;
        maintainLabel.textAlignment = NSTextAlignmentLeft;
        _maintainLabel = maintainLabel;
    }
    return _maintainLabel;
}

- (UISegmentedControl*)segmentedControl{
    if (!_segmentedControl) {
        NSArray * items = @[@"巡更",@"巡查",@"报障",@"清点"];
        UISegmentedControl * segmentControl=[[UISegmentedControl alloc]initWithItems:items];
        segmentControl.selectedSegmentIndex = 0;
        segmentControl.apportionsSegmentWidthsByContent = YES;//宽度自适应
        segmentControl.tintColor = [UIColor customGreenColor];
        [segmentControl addTarget:self action:@selector(segmentControlEvent:) forControlEvents:UIControlEventValueChanged];
        _segmentedControl = segmentControl;
    }
    return _segmentedControl;
}

- (UIView*)footView{
    if (!_footView) {
        
        UIView * footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        self.seeMoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(kGapH, 5, SCREEN_WIDTH-kGapH*2, 30)];
        self.seeMoreLabel.text = @"查看更多巡查记录";
        self.seeMoreLabel.textColor = [UIColor customTextGrayColor];
        self.seeMoreLabel.textAlignment = NSTextAlignmentCenter;
        [footView addSubview:self.seeMoreLabel];
        UITapGestureRecognizer * handleGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(footViewGestureRecognizer:)];
        [footView addGestureRecognizer:handleGesture];
        _footView = footView;
    }
    return _footView;
}
/*
- (UIButton*)addButton{
    if (!_addButton) {
        UIButton * addButton = [UIButton buttonWithType:UIButtonTypeCustom];
        CGFloat buttonSize = 50;
        [addButton setImage:[UIImage imageNamed:@"common_ledger_add"] forState:UIControlStateNormal];
        addButton.layer.masksToBounds = YES;
        addButton.frame = CGRectMake(SCREEN_WIDTH-kMarginW-buttonSize, SCREEN_HEIGHT-kMarginW-buttonSize, buttonSize, buttonSize);
        [addButton addTarget:self action:@selector(addButtonTouchEvent:) forControlEvents:UIControlEventTouchUpInside];
        _addButton = addButton;
    }
    return _addButton;
}
*/
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.addButton.hidden = NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    self.addButton.hidden = YES;

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
